package com.echo.servlet;

import com.echo.entity.Article;
import com.echo.entity.Category;
import com.echo.service.ArticleService;
import com.echo.service.CategoryService;
import com.echo.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 管理员文章管理Servlet
 * 处理文章的列表展示、分类筛选和删除操作
 */
@WebServlet({"/admin/article", "/admin/articleList.html", "/echo-network/admin/article", "/echo-network/admin/articleList.html"})
public class AdminArticleServlet extends BaseServlet {
    private static final Logger logger = LoggerFactory.getLogger(AdminArticleServlet.class);
    private ArticleService articleService = new ArticleService();
    private CategoryService categoryService = new CategoryService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 检查管理员权限
        if (!checkAdmin(req, resp)) {
            return;
        }

        String action = req.getParameter("action");
        if (action == null) {
            // 默认显示文章列表
            showArticleList(req, resp);
        } else if ("list".equals(action)) {
            showArticleList(req, resp);
        } else if ("delete".equals(action)) {
            deleteArticle(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 检查管理员权限
        if (!checkAdmin(req, resp)) {
            return;
        }

        String action = req.getParameter("action");
        if ("delete".equals(action)) {
            deleteArticle(req, resp);
        }
    }

    /**
     * 显示文章列表，支持分类筛选
     */
    private void showArticleList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            logger.info("开始处理文章列表请求");
            
            // 获取所有分类，用于筛选
            logger.info("获取所有分类");
            List<Category> categories = categoryService.getAllCategories();
            logger.info("获取到分类数量: {}", categories != null ? categories.size() : 0);
            req.setAttribute("categories", categories);

            // 获取筛选参数
            String categoryIdStr = req.getParameter("categoryId");
            logger.info("接收到的分类ID参数: {}", categoryIdStr);
            Integer categoryId = null;
            if (categoryIdStr != null && !categoryIdStr.isEmpty() && !"0".equals(categoryIdStr)) {
                categoryId = Integer.parseInt(categoryIdStr);
                logger.info("解析后的分类ID: {}", categoryId);
            }
            req.setAttribute("selectedCategoryId", categoryId);

            // 获取所有文章（管理员可以看到所有文章）
            List<Article> articles;
            if (categoryId != null) {
                // 按分类筛选
                logger.info("按分类ID {} 筛选文章", categoryId);
                articles = articleService.findByCategoryId(categoryId);
            } else {
                // 获取所有文章
                logger.info("获取所有文章");
                articles = articleService.findAllOrderByCreateTimeDesc();
            }
            
            logger.info("获取到文章数量: {}", articles != null ? articles.size() : 0);
            req.setAttribute("articles", articles);

            // 从URL参数中获取消息并设置到请求属性中
            String message = req.getParameter("message");
            String messageType = req.getParameter("messageType");
            if (message != null) {
                req.setAttribute("message", message);
                req.setAttribute("messageType", messageType != null ? messageType : "info");
            }

            // 转发到文章列表页面
            forward(req, resp, "/admin/articleList.html");
        } catch (Exception e) {
            logger.error("显示文章列表失败: {}", e.getMessage(), e);
            req.setAttribute("message", "获取文章列表失败: " + e.getMessage());
            forward(req, resp, "/error.html");
        }
    }

    /**
     * 删除文章
     */
    private void deleteArticle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取文章ID
            String articleIdStr = req.getParameter("id");
            if (articleIdStr == null || articleIdStr.isEmpty()) {
                ResponseUtils.sendJson(resp, "{\"success\":false, \"message\":\"文章ID不能为空\"}");
                return;
            }

            Integer articleId = Integer.parseInt(articleIdStr);
            
            // 调用服务层删除文章
            articleService.delete(articleId);

            // 返回成功响应
            // 设置成功消息和类型到请求属性
            req.setAttribute("message", "文章删除成功");
            req.setAttribute("messageType", "success");
            
            // 转发到文章列表页面，保留筛选条件
            showArticleList(req, resp);
        } catch (NumberFormatException e) {
            ResponseUtils.sendJson(resp, "{\"success\":false, \"message\":\"无效的文章ID\"}");
        } catch (Exception e) {
            logger.error("删除文章失败: {}", e.getMessage(), e);
            ResponseUtils.sendJson(resp, "{\"success\":false, \"message\":\"删除文章失败: " + e.getMessage() + "}");
        }
    }
}